package common

import (
	"crypto/md5"
	"encoding/hex"
	"sort"
	"strings"
)

func SortMaps(attributes map[string]string) string {
	var keys []string
	for k := range attributes {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	var signStr strings.Builder
	for _, key := range keys {
		if signStr.Len() > 0 {
			signStr.WriteString("&")
		}
		signStr.WriteString(key)
		signStr.WriteString("=")
		signStr.WriteString(attributes[key])
	}
	return signStr.String()
}

func Sign(attributes map[string]string, payKey string) string {
	var keys []string
	for k := range attributes {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	var signStr strings.Builder
	for _, key := range keys {
		if signStr.Len() > 0 {
			signStr.WriteString("&")
		}
		signStr.WriteString(key)
		signStr.WriteString("=")
		signStr.WriteString(attributes[key])
	}
	signStr.WriteString("&key=")
	signStr.WriteString(payKey)
	println("signStr=",signStr.String())
	// 计算MD5哈希值
	hasher := md5.New()
	hasher.Write([]byte(signStr.String()))
	hashBytes := hasher.Sum(nil)

	// 将哈希值转换为十六进制字符串并转换为大写
	sign := hex.EncodeToString(hashBytes)
	return strings.ToUpper(sign)
}

//func GetSignStr(data map[string]interface{}) string {
//	var keys []string
//	for k, _ := range data {
//		keys = append(keys, k)
//	}
//	sort.Strings(keys)
//	signKey := remove(keys, "sign")
//	str := ""
//	for _, k := range signKey {
//		if v, ok := data[k].(map[string]interface{}); ok {
//			substr := GetSignStr(v)
//			str += substr
//			continue
//		} else if v, ok := data[k].([]map[string]interface{}); ok {
//
//			for _, v1 := range v {
//				substr := GetSignStr(v1)
//				str += substr
//			}
//			continue
//		} else {
//			if data1, ok := data[k].(string); ok {
//				if len(data1) == 0 {
//					continue
//				}
//			}
//			str += fmt.Sprintf("&%s=%v", k, data[k])
//		}
//
//	}
//	return str
//}
